package com.example.search.service;


import com.alibaba.fastjson.JSON;
import com.common.to.es.SkuEsUpTo;
import com.example.search.config.ElasticSearchConfig;
import com.example.search.constant.EsConstant;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.Index;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ProductServiceImpl implements ProductService {

    @Autowired
    RestHighLevelClient client;

    @Override
    public Boolean productUp(List<SkuEsUpTo> skuList) throws IOException {

        BulkRequest bulkRequest = new BulkRequest();

        for (SkuEsUpTo sku : skuList) {
            IndexRequest request = new IndexRequest(EsConstant.ProductIndex);
//            IndexRequest request = new IndexRequest("bank");
            request.id(sku.getSkuId().toString());
            String skuJson = JSON.toJSONString(sku);
            request.source(skuJson, XContentType.JSON);
            bulkRequest.add(request);
        }
        BulkResponse bulk = client.bulk(bulkRequest, ElasticSearchConfig.COMMON_OPTIONS);

        if (bulk.hasFailures()) {
            List<String> list = Arrays.stream(bulk.getItems()).map(item -> {
                return item.getId();
            }).collect(Collectors.toList());
            log.error("这些商品上架失败了{}", list);
            return false;
        }
        return true;
    }
}
